package com.example.lwj.BaseDemo;

import android.text.TextUtils;

import com.example.lwj.application.MyAplication;
import com.example.lwj.utils.CommonUtls;
import com.example.lwj.utils.NetUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by lwj on 2016/11/1.
 */
public abstract class BaseDate {
    //网络出错
    public static final int Error_Net = 100;
    //请求出错
    public static final int Error_Request = 200;
   //请求的时间点
    public static final  long LONGTIME=1000*60*60*72;
    public static final  long SHORTTIME=1000*60*10;
    public static final  long NOTIME=0;
    public void getData(String path, long time) {
        if (time==0){
            getdatafromNet(path, time);
        }else {
            //首次进来先去查看本地  本地没有就去查看网络
            String data = getDatafromLocal(path, time);
            if (TextUtils.isEmpty(data)) {
                //如果本地没有那么网络获取
                getdatafromNet(path, time);
            } else {
                setResultData(data);
            }
        }
    }

    private void getdatafromNet(final String path, final long time) {
        //首先判断网络
        int zt = NetUtils.getNetWorkType(MyAplication.getContext());
        //网络有效开始访问
        if (zt != NetUtils.NETWORKTYPE_INVALID) {
            RequestParams requestParams = new RequestParams(path);
            x.http().get(requestParams, new Callback.CacheCallback<String>() {

                @Override
                public void onSuccess(String json) {
                    setResultData(json);
                    CommonUtls.exrun(new Runnable() {
                        @Override
                        public void run() {
                            writedatatoLocal("aaa", path, time);

                        }
                    });
                    //获取数据到本地
                }

                @Override
                public void onError(Throwable throwable, boolean b) {
                    setFailResult(Error_Request);
                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {

                }

                @Override
                public boolean onCache(String string) {
                    return false;
                }
            });
        } else {
            //网络问题
            setFailResult(Error_Net);  
        }


    }
    protected abstract void setFailResult(int error_Net);

    private void writedatatoLocal(String json, String path, long time) {
        File dir = MyAplication.getContext().getCacheDir();
        File file = new File(dir, path);
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        BufferedWriter buwrite = null;
        //获得缓冲流
        try {
            buwrite = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            //读取出来
            //计算时间
            buwrite.write(System.currentTimeMillis() + time + "\r\n");
            buwrite.write(json);
            buwrite.flush();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (buwrite!=null)
                buwrite.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    private String getDatafromLocal(String path, long time) {
        File dir = MyAplication.getContext().getCacheDir();
        File file = new File(dir, path);
        BufferedReader bureader = null;
        try {
            bureader = new BufferedReader(new FileReader(file.getAbsolutePath()));
            ;
            long time2 = Long.parseLong(bureader.readLine());
            //计算时间 之间时间加上有效时间

            if (System.currentTimeMillis() - time2 < 0) {
                //在有效时间之内
                StringBuffer stringBuffer = new StringBuffer();
                //开始读取
                String line = null;
                while ((line = bureader.readLine()) != null) {
                    stringBuffer.append(line);

                }
                return stringBuffer.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bureader!=null)
                bureader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public abstract void setResultData(String data);

}
